package com.lbj.core.ext

import android.util.Log
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.viewModelScope
import com.lbj.core.app.CoreVM
import com.lbj.mvvm.network.BaseResponse
import com.lbj.mvvm.work.Work
import com.lbj.mvvm.work.paresException
import com.lbj.mvvm.work.run
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

/**
 * 作者：李炳军
 * 创建日期：2021-03-29  15:48
 * 释义：
 */
/**
 * net request 会校验请求结果数据是否是成功
 * [request] request method
 * [work] request result
 * [showLoading] 配置是否显示等待框
 */
fun <T> CoreVM.launchRequest(
    request: suspend () -> BaseResponse<T>,
    work: MutableLiveData<Work<T>>,
    showLoading: Boolean = false,
    loadingMessage: String = "请求网络中...",
    show: Int = 0
) {
    viewModelScope.launch {
        runCatching {
            if (showLoading) work.value = Work.onLoading(loadingMessage)
            withContext(Dispatchers.IO) { request() }
        }.onSuccess {
            work.run(it, show)
        }.onFailure {
            Log.i("throwable", it.message ?: "")
            work.paresException(it)
        }
    }
}